﻿#include "Dialog_AddProxy.h"
#include "ui_Dialog_AddProxy.h"
#include "QMessageBox"
#include "QRandomGenerator"


Dialog_AddProxy::Dialog_AddProxy(QWidget *parent, std::function<void (QString, bool, uint16_t, uint16_t, bool)> addProxy):
    QDialog(parent),
    addProxyFunction(addProxy),
    ui(new Ui::Dialog_AddProxy)
{
    ui->setupUi(this);
}

Dialog_AddProxy::~Dialog_AddProxy()
{
    delete ui;
}



void Dialog_AddProxy::on_pushButton_add_clicked()
{
    if(ui->lineEdit_proxyName->text().isEmpty() || ui->lineEdit_serverPort->text().isEmpty() || ui->lineEdit_localPort->text().isEmpty()){
        QMessageBox::information(this,tr("信息"),tr("无效的映射信息！"));
        return;
    }

    if(ui->lineEdit_serverPort->text().toUInt() == 0){
        ui->lineEdit_serverPort->setText(QString::number(QRandomGenerator::global()->bounded(81,60000))); //随机端口，若端口不可用，将在服务器再次获取
    }

    if(this->addProxyFunction != nullptr){
        this->addProxyFunction(
            ui->lineEdit_proxyName->text(),
            ui->comboBox_proxyType->currentIndex() == 0,
            ui->lineEdit_serverPort->text().toUInt(),
            ui->lineEdit_localPort->text().toUInt(),
            ui->checkBox_persistent->isChecked()
            );
    }
    this->close();
}

void Dialog_AddProxy::on_pushButton_cancel_clicked()
{
    this->close();
}


//文本被编辑完成
void Dialog_AddProxy::on_lineEdit_serverPort_textEdited(const QString &arg1)
{
    ui->lineEdit_serverPort->setText(QString::number(arg1.toUInt()));
}


void Dialog_AddProxy::on_lineEdit_localPort_textEdited(const QString &arg1)
{
    ui->lineEdit_localPort->setText(QString::number(arg1.toUInt()));
}

